import { useRef } from 'react';
import { useChartHook } from '@/hooks';
import * as echarts from 'echarts';
import './index.less';

import { useEffect } from 'react';
import { useState } from 'react';
import mp4 from '../../assets/image/movie.mp4';
import videoBg from '../../assets/image/mapVideobg.png';

import { heatmapData, markDataList } from './data';
require('echarts-amap');
export default function ChartMap() {
  const chartRef = useRef(null);
  const Map = useRef(null);
  const heatmap = useRef(null);
  const markList = useRef([]);
  const dataRef = useRef(markDataList[0]);
  const [id, setId] = useState('asf924sdfgs');
  const [buttonPoint, setButtonPoint] = useState(true);
  const [buttonHot, setButtonHot] = useState(false);
  const [button3D, setButton3D] = useState(false);
  const [button2D, setButton2D] = useState(true);

  const [satelliteLayerUse, setSatelliteLayerUse] = useState(null);

  useEffect(() => {
    var obj = document.getElementById('amapjs');
    if (obj) {
      // 先让它加载完
      setTimeout(() => initMap(), 1000);
    } else {
      var url =
        'https://webapi.amap.com/maps?v=1.4.14&key=d49460bc26777722a5feea6d7d2d6e73&plugin=AMap.CustomLayer,AMap.Heatmap&callback=onLoad';
      window._AMapSecurityConfig = {
        securityJsCode: '2093d3d20536874e4b8ab507bc65f323',
      };
      var jsapi = document.createElement('script');
      jsapi.charset = 'utf-8';
      jsapi.src = url;
      jsapi.id = 'amapjs';
      document.head.appendChild(jsapi);
      window.onLoad = function () {
        initMap();
      };
    }
    return () => {
      var obj = document.getElementById('amapjs');
      if (obj) {
        document.getElementsByTagName('head')[0].removeChild(obj);
      }
    };
  }, []);

  const initMap = () => {
    let myChart;
    if (myChart != null && myChart != '' && myChart != undefined) {
      myChart.dispose();
    }
    if (myChart == null) {
      myChart = echarts.init(document.getElementById(id));
    }

    myChart.setOption({
      amap: {
        maxPitch: 60,
        pitch: 0, // 60 45 俯仰角
        viewMode: '3D',
        zoom: 17,
        expandZoomRange: true,
        zooms: [0, 20],
        // mapStyle: 'amap://styles/blue', //地图主题
        mapStyle: 'amap://styles/bb600e31122fb1e8180d1f77c9e052d0', //地图主题
        center: [116.318947, 39.942735],
        rotation: 0, //顺时针旋转角度
        resizeEnable: false,
      },
      animation: true,
      series: [],
    });

    Map.current = myChart.getModel().getComponent('amap').getAMap();
    var layer = myChart.getModel().getComponent('amap').getLayer();
    Map.current.setFitView();

    // 绘制点标记
    var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(15, -35) });
    markDataList.map((data) => {
      const markIcon = new AMap.Icon({
        size: new AMap.Size(60, 60),
        image: data.img,
        imageSize: new AMap.Size(60, 60),
      });

      // 将 icon 传入 marker
      const mark = new AMap.Marker({
        position: new AMap.LngLat(...data.position),
        icon: markIcon,
      }); //todo 渲染点信息,颜色可以自己根据数量判断,我们是让后端返回颜色
      let contentOne = `
<div class="tip-box">
  <div class="box-content">
  <div class="contentTitle">摄像头编号</div>
  <div class="contentVideo">
  <video
    class="my-video"
     controls='true'
      src=${mp4}
     poster=${videoBg}
      preload="auto"
       webkit-playsinline="true"
     playsInline='true'
      x-webkit-airplay="allow"
          x5-video-player-type="h5"
          x5-video-player-fullscreen="true"
          x5-video-orientation="portraint"
          style='object-fit: fill;border-radius: 1px'
          loop='true'
          muted='true'
        ></video>
  </div>
 </div>
  </div>
         `;
      let contentTwo = `<div class="tip-box">
<div class="box-content">
<div class="contentTitle">设备编号</div>
<div class="contentOther">

<div class='imgBox'></div>
<div class='infobox'>
<div><span class='title'>设备编号：</span>${data.number}</div>
<div><span class='title'>杀虫量：</span>${data.pestNumber}</div>
<div><span class='title'>电量：</span>${data.electricity}</div>
</div>

<div class='positionstyle'><span class='title'>定位信息：</span>${data.position}</div>
</div>
</div>
</div>
        `;
      mark.content = data.status ? contentOne : contentTwo;

      mark.on('click', markerClick);
      mark.emit('click', { target: mark });

      markList.current.push(mark);
    });

    // 将 markers 添加到地图
    Map.current.add(markList.current);

    //热力图

    Map.current.plugin(['AMap.Heatmap'], function () {
      //初始化heatmap对象
      heatmap.current = new AMap.Heatmap(Map.current, {
        radius: 25, //给定半径
        opacity: [0, 0.8],
        /*,
            gradient:{
                0.5: 'blue',
                0.65: 'rgb(117,211,248)',
                0.7: 'rgb(0, 255, 0)',
                0.9: '#ffea00',
                1.0: 'red'
            }
             */
      });
      //设置数据集：该数据为北京部分“公园”数据
      heatmap.current.setDataSet({
        data: heatmapData,
        max: 100,
      });
    });

    heatmap.current.hide();

    // 增加卫星图层
    var satelliteLayer = new AMap.TileLayer.Satellite();
    Map.current.add([satelliteLayer]);
    satelliteLayer.hide();

    function markerClick(e) {
      infoWindow.setContent(e.target.content);
      infoWindow.open(Map.current, e.target.getPosition());
    }

    //下面是确保高德地图渲染的时候，echarts同时也需要再次渲染一次，保持位置的同步
    layer.render = function () {
      myChart.setOption({});
    };

    setSatelliteLayerUse(satelliteLayer);
  };

  function changeMapStyle(v) {
    if (v == 1) {
      // satelliteLayerUse && satelliteLayerUse.hide();
    }
    satelliteLayerUse && satelliteLayerUse.show();
  }

  return (
    <div className="map-cont1">
      <div className="map-chart" id={id}></div>

      <div className="statusbox">
        <div className="one"> 正常 </div>
        <div className="two"> 异常 </div>
      </div>

      <div
        className="buttonPoint"
        style={{
          background: buttonPoint
            ? `url(${require('../../assets/image/buttonPointBgL.png')}) no-repeat center / cover`
            : `url(${require('../../assets/image/buttonPointBg.png')}) no-repeat center / cover`,
        }}
        onClick={() => {
          heatmap.current.hide();
          Map.current.setZoom(15, true);
          // Map.current.setCenter([113.66312, 34.755975], true);
          Map.current.add(markList.current);
          setButtonPoint(true);
          setButtonHot(!buttonHot);
        }}
      >
        点位图
      </div>
      {/* <div
        className="buttonHot"
        style={{
          background: buttonHot
            ? `url(${require('../../assets/image/buttonHotBgL.png')}) no-repeat center / cover`
            : `url(${require('../../assets/image/buttonHotBg.png')}) no-repeat center / cover`,
        }}
        onClick={() => {
          heatmap.current.show();
          // Map.current.setCenter([116.471019, 39.991893], true);
          // Map.current.setCenter([113.66312, 34.755975], true);
          Map.current.setZoom(10, true);
          Map.current.remove(markList.current);
          setButtonHot(!buttonHot);
          setButtonPoint(!buttonPoint);
        }}
      >
        热力图
      </div> */}

      {/* <div
        className="button2D"
        style={{
          background: button2D
            ? `url(${require('../../assets/image/button2DBgL.png')}) no-repeat center / cover`
            : `url(${require('../../assets/image/button2DBg.png')}) no-repeat center / cover`,
        }}
        onClick={() => {
          // Map.current && Map.current.destroy();
          Map.current.setPitch(0, true);
          Map.current.setRotation(0, true);
          setButton2D(!button2D);
          setButton3D(!button3D);
        }}
      >
        2D地图
      </div>
      <div
        className="button3D"
        style={{
          background: button3D
            ? `url(${require('../../assets/image/button3DBgL.png')}) no-repeat center / cover`
            : `url(${require('../../assets/image/button3DBg.png')}) no-repeat center / cover`,
        }}
        onClick={() => {
          Map.current.setPitch(65, true);
          Map.current.setRotation(45, true);
          setButton2D(!button2D);
          setButton3D(!button3D);
        }}
      >
        3D地图
      </div> */}

      {/* <div className="changeMapStyle">
        <span
          className=""
          onClick={() => {
            changeMapStyle(1);
          }}
        >
          地图
        </span>
        <span
          className=""
          onClick={() => {
            changeMapStyle(1);
          }}
        >
          混合
        </span>
      </div> */}
    </div>
  );
}
